﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;


namespace POC
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            UpdateAddressBook(); 
            AddressView.ItemActivate +=new EventHandler(AddressView_ItemActivate);
        }

        private void SubmitBtn_Click(object sender, EventArgs e)
        {
            AddressEntry temp = new AddressEntry();
            temp.Name = Nametxt.Text;
            temp.Email = Emailtxt.Text;
            if (SubmitBtn.Text == "Submit Create")
            {
                //create
                AddressEntryDAO.Add(temp);
                UpdateAddressBook();
            }
            else
            {
                AddressEntryDAO.Update(temp);
                UpdateAddressBook();
                SubmitBtn.Text = "Submit Create";
                //update
            }
            
        }
        public void UpdateAddressBook()
        {
            AddressView.Items.Clear();
            List<AddressEntry> list = AddressEntryDAO.LoadAll();
            for (int i = 0; i < list.Count; ++i)
            {
                string[] row = new string[3];
                row[0] = list[i].ID.ToString();
                row[1] = list[i].Name;
                row[2] = list[i].Email;
                AddressView.Items.Add(new ListViewItem(row));
            }
            Nametxt.Text = "";
            Emailtxt.Text = "";
        }
        public void AddressView_ItemActivate(Object sender, EventArgs e)
        {
            AddressEntryDAO.LastClicked.ID =Convert.ToInt32(((ListViewItem)AddressView.SelectedItems[0]).SubItems[0].Text);
            AddressEntryDAO.LastClicked.Name = ((ListViewItem)AddressView.SelectedItems[0]).SubItems[1].Text.ToString();
            AddressEntryDAO.LastClicked.Email = ((ListViewItem)AddressView.SelectedItems[0]).SubItems[2].Text.ToString();
            DeleteBtn.Enabled = true;
            UpdateBtn.Enabled = true;
            
        }

        private void UpdateBtn_Click(object sender, EventArgs e)
        {
            Nametxt.Text = AddressEntryDAO.LastClicked.Name;
            Emailtxt.Text = AddressEntryDAO.LastClicked.Email;
            SubmitBtn.Text = "Submit Update";
        }

        private void DeleteBtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Really delete?", "Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                AddressEntryDAO.Delete();
            }
            UpdateAddressBook();
        }

        private void CreateBtn_Click(object sender, EventArgs e)
        {
            Nametxt.Text = "";
            Emailtxt.Text = "";
            SubmitBtn.Text = "Submit Create";
        }
    }
}
